import React, { Component } from 'react'

import { Route } from 'react-router-dom'
import News from '../News'
import Index from '../Index'
import Profile from '../Profile'
import HoseList from '../HoseList'

// 导入tabbar
import { TabBar } from 'antd-mobile'

// 导入样式
import './index.css'

// 封装每一项的TabbarItem
const tabbarItems = [
  { title: '首页', icon: 'icon-ind', path: '/home' },
  { title: '找房', icon: 'icon-findHouse', path: '/home/list' },
  { title: '资讯', icon: 'icon-infom', path: '/home/news' },
  { title: '我的', icon: 'icon-my', path: '/home/profile' },
]

export default class Home extends Component {
  state = {
    // 默认选中的Tabbar选项
    selectedTab: this.props.location.pathname,
  }

  // 解决flex导航栏点击进行路由跳转的时候，Tabbar不高亮的问题，路由的信息通过props传递给组件
  componentDidUpdate(prevProps) {
    // console.log('上一次的路由信息', prevProps)
    // console.log('当前的路由信息', this.props)
    // 如果两次的路由跳转地址不一样
    if (this.props.location.pathname !== prevProps.location.pathname) {
      // 则对TabBar的默认选中项进行改变
      this.setState({
        selectedTab: this.props.location.pathname,
      })
    }
  }

  // TabbarItem结构封装方法
  renderTabbar = () => {
    return tabbarItems.map(item => (
      <TabBar.Item
        title={item.title}
        key={item.title}
        icon={<i className={`iconfont ${item.icon}`} />}
        selectedIcon={<i className={`iconfont ${item.icon}`} />}
        selected={this.state.selectedTab === item.path}
        onPress={() => {
          this.setState({
            selectedTab: item.path,
          })
          this.props.history.push(item.path)
        }}
      ></TabBar.Item>
    ))
  }

  render() {
    return (
      <div className="home">
        {/* 配置子路由规则 */}
        <Route path="/home/news" component={News}></Route>
        <Route exact path="/home" component={Index}></Route>
        <Route path="/home/profile" component={Profile}></Route>
        <Route path="/home/list" component={HoseList}></Route>

        {/* Tabbar */}
        <TabBar tintColor="#21b97a" noRenderContent={true} barTintColor="white">
          {this.renderTabbar()}
        </TabBar>
      </div>
    )
  }
}
